/**
 * Copyright 2025 Beijing Volcano Engine Technology Co., Ltd. All Rights Reserved.
 * SPDX-license-identifier: BSD-3-Clause
 */

 import Paused from '@/assets/AiImgs/paused.png';
 import Start from '@/assets/AiImgs/start.png';
import { useSelector } from 'react-redux';
import { RootState } from '@/store';
import Conversation from './Conversation';
import AudioController from './AudioController';
import utils from '@/utils/utils';
import style from './index.module.less';
import { useDispatch } from 'react-redux';
import React from 'react';
import {getTrainRecord} from '@/api/train'
import { setTimeIsStart,updateTimeReset } from '@/store/slices/room';
import { Link,useSearchParams,useNavigate } from 'react-router-dom';
interface Utterance {
  utterances: string;
  start_time: number;
  end_time: number;
}

interface AudioRecord {
  audio_url: string;
  record: Utterance[];
}

interface ApiResponse {
  code: number;
  msg: string;
  data: {
    list: AudioRecord[];
  };
}
function Room() {
  const [audioList, setAudioList] = React.useState<AudioRecord[]>([]);
  const [audioUrl,setaudioUrl]=React.useState('')
  const [isPlaying, setIsPlaying] = React.useState(false);
  const [showSubtitles, setShowSubtitles] = React.useState(true);
  const audioRef = React.useRef<HTMLAudioElement>(null);
  const [currentTime, setCurrentTime] = React.useState(0);
  const [isStart,setIsStart]=React.useState(true)
  const [currentAudioIdx, setCurrentAudioIdx] = React.useState(0);
  const [searchParams,setSearchParams] = useSearchParams()
  const dispatch = useDispatch();
 React.useEffect(() => {
  const trainee_id = searchParams.get('trainee_id')
  const picid=searchParams.get('picid')
  getTrainRecord({practice_id:picid,trainee_id})
      .then((data: ApiResponse) => {
        if (data.code === 2000) {
          setAudioList(data.data.list);
        }
      });
      return ()=>{
        dispatch(setTimeIsStart({ data:false }));
        dispatch(updateTimeReset({data:false}))
      }
  }, []);
  React.useEffect(() => {
    setCurrentTime(0);
    setIsPlaying(false);
    if (audioRef.current) {
      audioRef.current.currentTime = 0;
      audioRef.current.pause();
    }
  }, [currentAudioIdx]);
  const handleTimeUpdate = () => {
    if (audioRef.current) {
      setCurrentTime(audioRef.current.currentTime * 1000);
    }
  };


  const handlePlayPause = () => {
    if (!audioRef.current) return;
    dispatch(updateTimeReset({data:false}))
    if (isPlaying) {
      dispatch(setTimeIsStart({ data:false }));
      audioRef.current.pause();
      setIsPlaying(false);
    } else {
      dispatch(setTimeIsStart({ data:true }));
      audioRef.current.play();
      setIsPlaying(true);
      
    }
  };
  const currentAudio = audioList[currentAudioIdx];
  const visibleSubtitles = currentAudio?.record.filter(item => item.start_time <= currentTime) || [];
  return (
    <div className={`${style.wrapper} ${ style.mobile}`} style={{flex: 1,overflow: 'hidden'}}>
    {/* {utils.isMobile()?<AvatarMobileCard avatar={DoubaoAvatar} className={style.avatar}/>:<AvatarCard avatar={DoubaoAvatar} className={style.avatar} />} */}
    <Conversation className={style.conversation} msglist={visibleSubtitles}/>
    <div className='flex justify-center absolute w-screen left-0 px-8' style={{padding: '10px 0 10px'}}>
        {/* <AudioController className={style.controller} audio_url=''/> */}
        <div className={style.controller}>
        <audio
          ref={audioRef}
          src={currentAudio?.audio_url}
          onTimeUpdate={handleTimeUpdate}
          onEnded={() => {setIsPlaying(false);dispatch(setTimeIsStart({ data:false }));dispatch(updateTimeReset({data:true}))}}
          style={{ display: 'none' }}
        />
        {!isPlaying?<img className='w-7 h-7' style={{margin: '0 auto'}} src={Start} onClick={()=>{handlePlayPause()}}/>:<img className='w-7 h-7' style={{margin: '0 auto'}} onClick={()=>{handlePlayPause()}} src={Paused}/>}
        <div className='text-white mt-3 text-base'>{!isPlaying?'开始':'暂停'}</div>
    </div>
    </div>
  </div>
  );
}

export default Room;
